package com.yc.cloud.openai.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.openai.constants.OpenAiConstants;
import com.yc.cloud.openai.dto.TTSResultDTO;
import com.yc.cloud.openai.dto.resp.HFKJTTSResp;
import com.yc.cloud.openai.request.TTSParam;
import com.yc.cloud.openai.service.tts.TTSService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * 腾讯云语音转文字实现类
 */
@Service("HFKJTTSServiceImpl")
@Slf4j
public class HFKJTTSServiceImpl implements TTSService {
    String apiUrl = "https://saas.hafengkeji.com/ai/api/shuziren/yuyinhecheng";
    String GENDER_MAN = "1";
    String GENDER_WOMAN = "0";
    String gender = GENDER_WOMAN;

    int MAX_TEXT_LENGTH = 150;

    @Override
    public TTSResultDTO getTTSResult(TTSParam param) {
        var content = param.getContent();
        //文件转baseFile
        if (StrUtil.isNotEmpty(content)) {
            if (content.length() > MAX_TEXT_LENGTH) {
                log.info("HFKJTTSServiceImpl内容过长,长度为{}", content.length());
                content = content.substring(0, MAX_TEXT_LENGTH);
                log.info("HFKJTTSServiceImpl裁剪后长度为{}", content.length());
            }
            if (OpenAiConstants.GENDER_MAN.equals(param.getGender())) {
                gender = GENDER_MAN;
            } else {
                gender = GENDER_WOMAN;
            }
            // 构建请求体
            String requestBody = JSONUtil.createObj().set("text", content).set("gender", gender).set("codec", "wav").toString();
            log.info("getTTSResult requestBody-->{}", requestBody);
            // 发送 POST 请求
            val ttsStartTime = System.currentTimeMillis();
            try (HttpResponse response = HttpRequest.post(apiUrl).header("Content-Type", "application/json").body(requestBody) // 设置请求体
                    .execute()) {
                val ttsEndTime = System.currentTimeMillis();
                val costTime = ttsEndTime - ttsStartTime;
                log.info("HFKJ TTS Spend times {}", costTime);
                val result = response.body();
                log.debug("getTTSResult Result-->{}", result);
                val hfkjttsResp = JSONUtil.toBean(result, HFKJTTSResp.class);
                if (hfkjttsResp.getCode() != 0) {
                    log.error(hfkjttsResp.getMsg());
                    return null;
                }
                val ttsResultDTO = new TTSResultDTO();
                ttsResultDTO.setResult(hfkjttsResp.getData().getAudio());
                ttsResultDTO.setCostTime(costTime);
                return ttsResultDTO;
            }
        }
        return null;
    }

    @Override
    public Mono<TTSResultDTO> getTTSResultByMono(TTSParam param) {
        return null;
    }

}
